from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from common.pagination import CustomerPagination
from system.models import Menu
from system.serializer import MenuSerializer
from system.server.menu_server import MenuServer


class MenuViewSet(viewsets.ModelViewSet):
    # 指定序列化器类
    serializer_class = MenuSerializer
    # 指定权限类， 要求用户认证
    permission_classes = [IsAuthenticated]
    # 使用自定义分页
    pagination_class = CustomerPagination

    # 注入菜单服务
    menu_server = MenuServer()

    # 分页获取菜单列表
    def menu_list(self, request, *args, **kwargs):
        queryset = Menu.objects.all()
        page_queryset = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page_queryset, many=True)
        return self.get_paginated_response(serializer.data)

    # 获取菜单树
    def menu_tree_list(self, request, *args, **kwargs):
        queryset = Menu.objects.all()
        tree_data = self.menu_server.parse_tree(queryset)
        return Response(tree_data)

